// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// g [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// A [github] https://github.com/rhymelph

import 'dart:io';
import 'dart:typed_data';

import 'package:base_plugin/base_plugin.dart';
import 'package:cropper/cropper.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/cupertino.dart';
import 'dart:ui' as ui;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class EditPhotoProvider extends BaseProvider {
  CropController cropController;

  String filepath;

  bool isFromPhoto;

  @override
  Future get dataFuture => null;

  void initData(String filepath, bool isFromPhoto) {
    this.filepath = filepath;
    this..isFromPhoto = isFromPhoto;
    if (isFromPhoto == true) {
      cropController = CropController(aspectRatio: 1);
    } else {
      cropController = CropController(aspectRatio: 9 / 16);
    }
  }

  void onRotate() {
    if (isFromPhoto == true) {
    } else {
      if (cropController.aspectRatio == 9 / 16) {
        cropController.aspectRatio = 16 / 9;
      } else {
        cropController.aspectRatio = 9 / 16;
      }
    }
    if (cropController.rotation == 0) {
      cropController.rotation = -90;
    } else {
      cropController.rotation = 0;
    }
  }

  void onDone() async {
    obtainContext?.call((context) async {
      BaseConfig.dialogBase
          .showLoadingDialog(context: context, text: 'Loading');
      final image =
          await cropController.crop(pixelRatio: ui.window.devicePixelRatio);
      final directory = await getTemporaryDirectory();
      String filename =
          '${path.basenameWithoutExtension(filepath)}_crop${path.extension(filepath)}';
      final cropDirectory = Directory(path.join(directory.path, 'crop'));
      if (!cropDirectory.existsSync()) {
        await cropDirectory.create();
      }
      final cropFile = File(path.join(cropDirectory.path, filename));
      if (!cropFile.existsSync()) {
        await cropFile.create();
      }
      ByteData data = await image.toByteData(format: ui.ImageByteFormat.png);
      await cropFile.writeAsBytes(data.buffer.asUint8List());
      print(cropFile.lengthSync());

      //退出加载动画，退出页面
      Navigator.of(context)..pop()..pop(cropFile.path);
    });
  }

  void onRetakePhotoOrSelect() {
    obtainContext?.call((context) {
      Navigator.of(context).pop();
      if (isFromPhoto == true) {
        Routes.navigateTo(RouterGenProviders.selectPhotoPage, replace: true);
      } else {
        Routes.navigateTo(RouterGenProviders.ocrCameraPage, replace: true);
      }
    });
  }
}
